﻿using Newtonsoft.Json.Linq;
using NLog;
using ReportMealManagementSystem.Business;
using ReportMealManagementSystem.Entity;
using ReportMealManagementSystem.Tool;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ReportMealManagementSystem
{
    /// <summary>
    /// UserRecharge.xaml 的交互逻辑
    /// </summary>
    public partial class UserRecharge : UserControl
    {
        private Logger logger = LogManager.GetCurrentClassLogger();
        Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        int districtID = int.Parse(ConfigurationManager.AppSettings["districtID"]);
        BasicInfo basicInfo = new BasicInfo();
        JArray mealUsers = new JArray();

        public UserRecharge()
        {
            InitializeComponent();
        }

        private void GetMealUserInfo()
        {
            string msg = "";
            JObject joMealUserParam = new JObject();
            joMealUserParam["PageIndex"] = 1;
            joMealUserParam["PageSize"] = 10000;
            joMealUserParam["DistrictID"] = districtID;
            int totalNumber = 0;
            int totalPage = 0;
            mealUsers = basicInfo.GetData(joMealUserParam, "gbt/UserVerify/UserListInfo", "用户", ref totalNumber, ref totalPage, ref msg);
            if (mealUsers != null)
            {
                JObject joItem = new JObject();
                List<SelectedItem> selectedItems = new List<SelectedItem>();
                selectedItems.Add(new SelectedItem
                {
                    ID = null,
                    Name = ""
                });
                for (int index = 0; index < mealUsers.Count; index++)
                {
                    joItem = (JObject)mealUsers[index];
                    selectedItems.Add(new SelectedItem
                    {
                        ID = (int)mealUsers[index]["userID"],
                        Name = (string)mealUsers[index]["number"] + "(" + (string)mealUsers[index]["name"] + ")"
                    });
                }

                cbNumber.Dispatcher.Invoke(new Action(delegate
                {
                    cbNumber.ItemsSource = selectedItems;
                    cbNumber.SelectedIndex = 0;
                }));
            }
        }

        private void Recharge()
        {
            string message = "";
            JObject joParam = new JObject();
            SystemParamSet.Dispatcher.Invoke(new Action(delegate {
                joParam["UserID"] = (int)cbNumber.SelectedValue;
                decimal value = 0;
                if (!string.IsNullOrEmpty(txtMoney.Text.Trim()))
                {
                    value = decimal.Parse(txtMoney.Text.Trim());
                }
                joParam["Value"] = value;
                joParam["DistrictID"] = districtID;
                joParam["Creator"] = Global.MealUser.UserID;
                joParam["Remark"] = txtRemark.Text.Trim();
            }));
            bool result = basicInfo.OptDataInfoNew(joParam, "gbt/UserStoredValue/OptUserStoredValue", ref message);
            this.message.Dispatcher.Invoke(new Action(delegate {
                this.message.Content = message;
            }));
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            _loading.Visibility = Visibility.Visible;
            Task task = new Task(new Action(delegate {
                GetMealUserInfo();
            }));
            task.Start();
            task.ContinueWith((t) => {
                _loading.Dispatcher.Invoke(new Action(delegate {
                    _loading.Visibility = Visibility.Collapsed;
                    txtRemark.Text = "账户充值";
                }));
            });
        }

        private void cbNumber_KeyUp(object sender, KeyEventArgs e)
        {
            List<SelectedItem> dicNumberVars = new List<SelectedItem>();
            if (mealUsers != null)
            {
                for (int index = 0; index < mealUsers.Count; index++)
                {
                    if (mealUsers[index]["name"].ToString().Contains(cbNumber.Text.Trim()) || mealUsers[index]["number"].ToString().Contains(cbNumber.Text.Trim())
                        || mealUsers[index]["name"].ToString().Contains(cbNumber.Text.Trim().ToLower()) || mealUsers[index]["number"].ToString().Contains(cbNumber.Text.Trim().ToLower())
                        || mealUsers[index]["name"].ToString().Contains(cbNumber.Text.Trim().ToUpper()) || mealUsers[index]["number"].ToString().Contains(cbNumber.Text.Trim().ToUpper()))
                    {
                        dicNumberVars.Add(new SelectedItem
                        {
                            ID = (int)mealUsers[index]["userID"],
                            Name = mealUsers[index]["number"].ToString() + "(" + mealUsers[index]["name"].ToString() + ")"
                        });
                    }
                }
                this.cbNumber.ItemsSource = "";
                cbNumber.ItemsSource = dicNumberVars.OrderBy(t => t.ID);
                this.cbNumber.SelectedIndex = -1;
                cbNumber.IsDropDownOpen = true;
            }
        }

        private void cbNumber_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbNumber.SelectedValue != null)
            {
                var userID = (int)cbNumber.SelectedValue;
                var mealUser = (JObject)mealUsers.Where(t => (int)t["userID"] == userID).FirstOrDefault();
                lblName.Content = (string)mealUser["name"];
                lblMobile.Content = (string)mealUser["mobile"];
                lblDistrictName.Content = (string)mealUser["districtName"];
                //txtMoney.Text = (string)mealUser["value"];
            }
            else
            {
                lblName.Content = "";
                lblMobile.Content = "";
                lblDistrictName.Content = "";
                txtMoney.Text = "";
            }
        }

        private void btnRecharge_Click(object sender, RoutedEventArgs e)
        {
            if (cbNumber.SelectedValue == null)
            {
                this.message.Content = "请选择用户";
                return;
            }
            _loading.Visibility = Visibility.Visible;
            Task task = new Task(new Action(delegate {
                Recharge();
            }));
            task.Start();
            task.ContinueWith((t) => {
                _loading.Dispatcher.Invoke(new Action(delegate {
                    _loading.Visibility = Visibility.Collapsed;
                    txtMoney.Text = "";
                }));
            });
        }

        private void txtMoney_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            var textBox = sender as TextBox;

            if ((e.Key == Key.OemPeriod && textBox.Text.Contains(".")) || e.Key == Key.OemPeriod && string.IsNullOrWhiteSpace(textBox.Text))
            {
                e.Handled = true;
                return;
            };

            if (!((e.Key >= Key.D0 && e.Key <= Key.D9)
                || e.Key == Key.Delete || e.Key == Key.Back || e.Key == Key.OemPeriod
                || e.Key == Key.Tab || e.Key == Key.OemBackTab
                || e.Key == Key.Left || e.Key == Key.Right || e.Key == Key.Up || e.Key == Key.Down)
                || (e.KeyboardDevice.Modifiers == ModifierKeys.Control && e.Key == Key.A))
            {
                if (e.KeyboardDevice.Modifiers != ModifierKeys.Control)
                {
                    e.Handled = true;
                }
            }
        }
    }
}
